//
//  RankViewController.swift
//  Spookiness
//
//  Created by 腾億 on 2017/12/6.
//  Copyright © 2017年 tml. All rights reserved.
//

import UIKit

class RankViewController: BaseViewController {

    ///数据源
    fileprivate var rankList = [RankingModel]()
    
    fileprivate lazy var tableView: UITableView = {
       let tv = UITableView(frame: .zero, style: .plain)
        tv.backgroundColor = kRGBA(r: 242, g: 242, b: 242, a: 1)
        tv.separatorStyle = .none
        tv.delegate = self
        tv.dataSource = self
        tv.tableFooterView = UIView()
        tv.register(RankTableViewCell.self, forCellReuseIdentifier: "RankTableViewCell")
        tv.rowHeight = kSCREEN_WIDTH * 0.4
        tv.refrshHead = RefreshGifHeader{
            self.loadData()
        }
        return tv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        
        loadData()
        
        setUpSnap()
        // Do any additional setup after loading the view.
    }
    
    fileprivate func loadData() {
        NetworkTool.loadHomeRankingData {[weak self] (rankingModel) in
            for rankItem in rankingModel.rankinglist {
                self?.tableView.refrshHead.endRefreshing()
                self?.rankList.append(rankItem)
                self?.tableView.reloadData()
            }
        }
    }
    
    fileprivate func setUpSnap() {
        view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(view.snp.bottom).offset(-2*kTabbarHeight)
        }
    }
    
}

extension RankViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rankList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RankTableViewCell", for: indexPath) as! RankTableViewCell
        cell.rankModel = rankList[indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView.deselectRow(at: indexPath, animated: true)
        let model = rankList[indexPath.row]
        let vc = HomeComicsListViewController(argCon: model.argCon, argName: model.argName ?? "", argValue: model.argValue)
        vc.title = "\(model.title ?? "")榜"
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}









